package com.yun.csv2db.writer;

import com.yun.csv2db.entity.Student;
import com.yun.csv2db.entity.enums.SexEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class StudentItemWriter implements ItemWriter<Student> {
    private static final String GET_STUDENT = "select * from STUDENT where id = ?";
    private static final String INSERT_STUDENT = "insert into STUDENT (id,name,sex,birth_date,home_address,school,grade,update_time,create_time) values (?,?,?,?,?,?,?,?,?)";
    private static final String UPDATE_STUDENT = "update STUDENT set name = ?, sex = ?, birth_date = ?, home_address = ?, school = ?, grade = ?, update_time = ? where id = ?";
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void write(List<? extends Student> students) throws Exception {
        for (Student student : students) {
            //查看是否有对应的数据
            List<Student> studentList = jdbcTemplate.query(GET_STUDENT, new Object[]{student.getId()}, new RowMapper<Student>() {
                public Student mapRow(ResultSet resultSet, int rowNum) throws SQLException {
                    Student s = new Student();
                    s.setId(resultSet.getInt("id"));
                    s.setName(resultSet.getString("name"));
                    s.setSex(SexEnum.getEnumFromString(resultSet.getString("sex")));
                    s.setBirthDate(resultSet.getString("birth_date"));
                    s.setHomeAddress(resultSet.getString("home_address"));
                    s.setSchool(resultSet.getString("school"));
                    s.setGrade(resultSet.getString("grade"));
                    s.setUpdateTime();
                    return s;
                }
            });
            //有数据更新
            if (studentList.size() > 0) {
                jdbcTemplate.update(UPDATE_STUDENT, student.getName(), student.getSex().name(), student.getBirthDate(), student.getHomeAddress(),
                        student.getSchool(), student.getGrade(), student.getUpdateTime(), student.getId());
                logger.info("Update successful.");
            }
            //没有数据就插入
            else {
                jdbcTemplate.update(INSERT_STUDENT, student.getId(), student.getName(), student.getSex().name(), student.getBirthDate(),
                        student.getHomeAddress(), student.getSchool(), student.getGrade(), student.getUpdateTime(), student.getCreateTime());
                logger.info("Insert successful.");
            }
        }
    }
}
